package org.lboot.llog.aspect;

import cn.hutool.core.net.NetUtil;
import cn.hutool.extra.servlet.ServletUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.lboot.core.domain.ResponseDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.List;

@Slf4j
@Aspect
@Component
public class ReqFilterAspect {

    @Value("#{'${llog.ip.allows:127.0.0.1}'.split(',')}")
    public List<String> allows;
    @Pointcut("@annotation(org.lboot.llog.anno.ReqFilter)")
    public void ReqFilter(){}


    @SneakyThrows
    @Around("ReqFilter()")
    public Object handleReqFilter(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        //log.info(request.getRemoteAddr());
        String clientIp = ServletUtil.getClientIP(request);
        InetAddress address = InetAddress.getByName(clientIp);
        // 是本地地址
        if (address.isAnyLocalAddress() || address.isLoopbackAddress()){
            return joinPoint.proceed();
        } else {
            if (!allows.isEmpty() && allows.contains(clientIp)){
                return joinPoint.proceed();
            }else {
                log.error("【{}】非授权IP", clientIp);
                return ResponseDTO.wrap(HttpStatus.FORBIDDEN,"非授权访问地址");
            }
        }
    }
}
